package mark.tom.friend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewTreeObserver;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flaviofaria.kenburnsview.KenBurnsView;
import com.hanks.htextview.fall.FallTextView;
import com.liaoinstan.springview.container.AcFunFooter;
import com.liaoinstan.springview.container.AcFunHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.squareup.phrase.Phrase;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import mark.tom.friend.app.CustomApplication;
import mark.tom.friend.base.activity.BaseActivity;
import mark.tom.friend.base.util.RxViewUtil;
import mark.tom.friend.bean.bo.AppInfoBO;
import mark.tom.friend.bean.vo.AppInfoVO;
import mark.tom.friend.component.DaggerMainComponent;
import mark.tom.friend.consts.ActivityRouterConsts;
import mark.tom.friend.consts.BundleKeyConsts;
import mark.tom.friend.contract.MainContract;
import mark.tom.friend.module.MainModule;
import mark.tom.friend.presenter.MainPresenter;
import mark.tom.friend.provider.ISystemProvider;
import mark.tom.friend.roll.BuildConfig;
import mark.tom.friend.roll.R;
import mark.tom.friend.view.adapter.MainListAdapter;
import timber.log.Timber;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@Route(path = ActivityRouterConsts.ROUTER_APP_MAIN)
public class MainActivity extends BaseActivity implements MainContract.View {

    private final static String APP_VERSION_NAME_TEMPLATE = "version_name";
    private final static String APP_VERSION_TEMPLATE = "v{" + APP_VERSION_NAME_TEMPLATE + "}";

    @Autowired Toolbar mainToolBar;
    @Autowired FallTextView mainTitleTextView;
    @Autowired FloatingActionButton mainSearchButton;
    @Autowired KenBurnsView mainToolBarBgImageView;
    @Autowired SpringView mainListSpringView;
    @Autowired RecyclerView mainListView;
    @Autowired public ISystemProvider systemProvider;

    @Autowired(innerWired = true) @Inject MainPresenter mPresenter;

    private int hintIndex = 0;
    private CharSequence[] titleHints = null;
    // 列表适配器
    private MainListAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.layout_main;
    }

    @Override
    protected void onCreate(View contentView, Bundle savedInstanceState) {
        // 设置双击返回
        setBackAwayMode(BACK_WAY_DOUBLE);
        // 注入数据
        DaggerMainComponent.builder()
                .appComponent(CustomApplication.get(this).getAppComponent())
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
        // 使用路由框架初始化
        ARouter.getInstance().inject(this, mPresenter, contentView, savedInstanceState);
        // 初始化ToolBar显示信息
        setToolBar(mainToolBar);
        titleHints = new CharSequence[] {
                getString(R.string.app_name),
                BuildConfig.APPLICATION_ID,
                Phrase.from(APP_VERSION_TEMPLATE)
                        .put(APP_VERSION_NAME_TEMPLATE, BuildConfig.VERSION_NAME)
                        .format()
        };
        // 初始化控件
        initRecyclerView();
        // 绑定控件事件
        bindViewListener();
        // 加载数据
        mPresenter.onStart();
    }

    private void initRecyclerView() {
        mainListView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mainListView.setHasFixedSize(true);
        mAdapter = new MainListAdapter();
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        mAdapter.bindToRecyclerView(mainListView);
        // 不允许刷新和不允许加载更多
        mainListSpringView.setGive(SpringView.Give.NONE);
        mainListSpringView.setType(SpringView.Type.FOLLOW);
        mainListSpringView.setHeader(new AcFunHeader(this, 0));
        mainListSpringView.setFooter(new AcFunFooter(this, 0));
    }

    private void bindViewListener() {
        Consumer<View> viewConsumer =  new Consumer<View>() {
            @Override
            public void accept(@NonNull View view) {
                switch (view.getId()) {
                    case R.id.mainSearchButton: {
                        // 跳转到选择APP界面
                        ARouter.getInstance()
                                .build(ActivityRouterConsts.ROUTER_APP_LIST)
                                .direction(MainActivity.this, MainPresenter.REQUEST_CODE_SELECT_APP);
                        break;
                    }
                    case R.id.mainTitleTextView: {
                        // 切换标题文字
                        hintIndex = hintIndex >= titleHints.length - 1 ? 0 : hintIndex + 1;
                        mainTitleTextView.animateText(titleHints[hintIndex]);
                        break;
                    }
                    default: {
                        break;
                    }
                }
            }
        };
        RxViewUtil.bindViewClickListener(mainSearchButton, bindToLifecycle(), viewConsumer);
        RxViewUtil.bindViewClickListener(mainTitleTextView, bindToLifecycle(), viewConsumer);
        // 设置标题栏文字
        mainTitleTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mainTitleTextView.animateText(titleHints[0]);
            }
        });
        mainListView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                AppInfoBO appInfo = (AppInfoBO) mAdapter.getItem(position);
                if (null == appInfo) {
                    return;
                }
                // 跳转到设置界面
                ARouter.getInstance()
                        .build(ActivityRouterConsts.ROUTER_APP_INFO)
                        .withParcelable(BundleKeyConsts.BUNDLE_KEY_APP_INFO, appInfo)
                        .direction(MainActivity.this);
            }
        });
    }

    @Override
    public void refreshListView() {
        mPresenter.listAppInfo()
                .compose(this.<AppInfoBO>bindToLifecycle())
                .subscribe(new Observer<AppInfoBO>() {
                    List<AppInfoVO> appInfoList = new ArrayList<AppInfoVO>();

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        appInfoList.clear();
                    }

                    @Override
                    public void onNext(@NonNull AppInfoBO appInfoBO) {
                        appInfoBO.setIcon(systemProvider.getAppIconByPackageName(appInfoBO.getPackageName()));
                        appInfoList.add(appInfoBO);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Timber.e(e);
                    }

                    @Override
                    public void onComplete() {
                        // 刷新界面
                        mAdapter.setNewData(appInfoList);
                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && null != data) {
            Observable<Long> result = mPresenter.onResult(requestCode, data.getParcelableExtra(BundleKeyConsts.BUNDLE_KEY_APP_INFO));
            if (null != result) {
                result.compose(this.<Long>bindToLifecycle())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(@NonNull Long aLong) {
                                // 刷新视图
                                refreshListView();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(@NonNull Throwable throwable) {
                                Timber.e(throwable);
                            }
                        });
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mainToolBarBgImageView.resume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mainToolBarBgImageView.pause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mainToolBarBgImageView.restart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 回收mPresenter
        mPresenter.onDestroy();
    }

}
